import * as changeCase from 'change-case';

import { MenuType } from '../../../../../lib/enums';

const buttonitemTpl = (item) => {
  const variableName = `has${changeCase.pascalCase(item.code)}Authority`;
  return {
    code: `\tconst ${variableName} = useHasButtonAuth(ButtonEnum.${item.code});\n`,
    name: variableName,
  };
};

const menuitemTpl = (item) => {
  const variableName = `has${changeCase.pascalCase(item.code)}`;
  return {
    code: `\tconst ${variableName} = useHasButtonAuth(MenuEnum.${item.code});\n`,
    name: variableName,
  };
};

const genMainCode = (tpl, data) => {
  const res = data.reduce(
    (acc, item) => {
      const { code, name } = tpl(item);
      acc.plainCode += code;
      acc.returnCode += `\t\t${name},\n`;
      return acc;
    },
    { plainCode: '', returnCode: '\treturn {\n' },
  );
  res.returnCode += `\t}\n`;
  return res.plainCode + res.returnCode;
};

const tpl = (buttonCode, menuCode) => {
  return `
import { ButtonEnum, MenuEnum } from '@/lib/enums' // 改成自己的枚举路径
import { useHasButtonAuth } from '@/hooks/permissions' // 改成自己的权限判断路径

export const useButtonPermission = () =>{
${buttonCode}
}

export const useMenuPermission = () =>{
${menuCode}
}

`;
};

export const toReactHooksCode = (data) => {
  const buttonList = data.filter((item) => MenuType.isButton(item.type));
  const menuList = data.filter((item) => MenuType.isMenu(item.type));
  return tpl(
    genMainCode(buttonitemTpl, buttonList),
    genMainCode(menuitemTpl, menuList),
  );
};
